import md5 from 'js-md5';
import axios from 'axios';
import Config from './config.js'
import { ElMessage } from 'element-plus'
import router from '@/common/router.js'
import QS from 'qs' // 引入qs模块，用来序列化post类型的数据


axios.defaults.timeout = 10000;//设置请求超时

//判断是否生产环境
// if(Config.dev == 1){
// 	axios.defaults.baseURL = '/myApi/';//开发环境
// }else{
	axios.defaults.baseURL = Config.baseUrl;//生产环境
// }

axios.defaults.withCredentials=true;
//post请求头的设置
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求拦截器
axios.interceptors.request.use(
  config => {
	// 头部参数
	config.headers.token = localStorage.getItem('token') || '';
	config.headers.client = 'admin';
	config.headers.lang = localStorage.getItem('lang') || 'zh';
    return config;
	
    return config;
  },
  error => {
    return Promise.error(error);
  }
)

// 响应拦截器
axios.interceptors.response.use(
    response => {
        if(response.status == 200){
            if(response.data.code == 401){
                ElMessage.error('token过期，请重新登录')
                localStorage.removeItem('token')
                localStorage.removeItem('login')
                router.push({path: "/login"})
                return Promise.resolve(response);
            }else{
                return Promise.resolve(response);
            }
        }else{
            ElMessage.error('服务器错误，请联系管理员')
            return Promise.resolve(response);
        }
    },
    error => {
        ElMessage.error('服务器异常，请联系管理员')
        return Promise.reject(error.response);
    }
)

/**
  * get方法，对应get请求
  * @param {String} url [请求的url地址]
  * @param {Object} params [请求时携带的参数]
  */
 function get(url, params){
    return new Promise((resolve, reject) =>{
        axios.get(url, {
            params:params
        })
        .then(res => {
            resolve(res.data);
        })
        .catch(err => {
            reject(err)
        })
    });
}

/**
  * post方法，对应post请求
  * @param {String} url [请求的url地址]
  * @param {Object} params [请求时携带的参数]
  */
function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, QS.stringify(params))
        .then(res => {
            resolve(res.data);
        })
        .catch(err => {
            reject(err)
        })
    });
}

export default {post,get}

